import { _decorator, Collider2D, Color, Component, Contact2DType, IPhysics2DContact, Node, Sprite, tween } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TransparencyController')
export class TransparencyController extends Component {
    colliders: Collider2D[] = null;
    sprite: Sprite = null;
    onLoad(){
        this.colliders = this.node.getComponents(Collider2D);
        this.sprite = this.node.getComponent(Sprite);
    }
    start() {
        this.colliders.forEach(collider => {
            //判断碰撞体的tag是否为1，将该碰撞体作为判断遮挡传感器，对应碰撞体组件里tag记得改为1
            if(collider.tag == 1){
                collider.on(Contact2DType.BEGIN_CONTACT, this.activeTransparency, this);
                collider.on(Contact2DType.END_CONTACT, this.endTransparency, this);
            }
        })
    }
    
    activeTransparency(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
        if(otherCollider.node.name == 'Player1'){
            // this.sprite.color = new Color(255, 255, 255, 128);
            // 定义起始颜色和结束颜色
            const endColor = new Color(255, 255, 255, 65);
            // 使用 cc.tween 创建颜色过渡动画
            tween(this.sprite)
                .to(0.2, { color: endColor })  // 在0.2秒内过渡到endColor
                .start(); 
        }
    }
    endTransparency(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if(otherCollider.node.name == 'Player1') {
            // this.sprite.color = new Color(255, 255, 255, 255)
            const endColor = new Color(255, 255, 255, 255);
            // 使用 cc.tween 创建颜色过渡动画
            tween(this.sprite)
                .to(0.2, { color: endColor})  // 在0.2秒内过渡到endColor
                .start();
        }
    }

    onDestroy(){
        this.colliders.forEach(collider => {
            if(collider.tag == 1){
                collider.off(Contact2DType.BEGIN_CONTACT, this.activeTransparency, this);
                collider.off(Contact2DType.END_CONTACT, this.endTransparency, this);
            }
        })
    }

}


